<script setup lang="tsx">
import { ContentWrap } from '@/components/ContentWrap'
import { useI18n } from '@/hooks/web/useI18n'
import { Table, TableColumn } from '@/components/Table'
import {
  getReCheckProblems,
  addProblemRecheck,
  getPalyCutFileApi,
  SetHomeShowApi
} from '@/api/table'
import { ref, unref, reactive, onMounted } from 'vue'
import { useTable } from '@/hooks/web/useTable'
import { Search } from '@/components/Search'
import { Form, FormSchema } from '@/components/Form'
import { BaseButton } from '@/components/Button'
import { useValidator } from '@/hooks/web/useValidator'
import { Dialog } from '@/components/Dialog'
import { useForm } from '@/hooks/web/useForm'
import { Descriptions, DescriptionsSchema } from '@/components/Descriptions'
import { ElMessage } from 'element-plus'
import { searchSchema, rowStyleFC } from './util'
import { useUserStoreWithOut } from '@/store/modules/user'
const userStore = useUserStoreWithOut()
const { t } = useI18n()
const { required } = useValidator()
const { formRegister, formMethods } = useForm()
const { setValues, getFormData, getElFormExpose } = formMethods
const columns: TableColumn[] = [
  // {
  //   field: 'workTypeName',
  //   label: '作业类型',
  //   sortable: true
  // },
  {
    field: 'problemTypeName',
    label: t('problem.problemType'),
    sortable: true
  },

  {
    field: 'fileName',
    label: t('common.fileName'),
    sortable: true
  },
  {
    field: 'stationName',
    label: '采集站',
    sortable: true
  },
  {
    field: 'depName',
    label: '部门',
    sortable: true
  },

  {
    field: 'userName',
    label: '用户',
    sortable: true
  },
  {
    field: 'deviceNo',
    label: '设备编号',
    sortable: true
  },
  {
    field: 'fileTime',
    label: '拍摄时间',
    sortable: true
  },
  {
    field: 'collectTime',
    label: '采集时间',
    sortable: true
  },
  {
    field: 'checkTime',
    label: '审查时间',
    sortable: true
  },
  {
    field: 'correctContent',
    label: '整改措施',
    sortable: true
  },
  {
    field: 'correctTime',
    label: '整改时间',
    sortable: true
  },
  {
    field: 'checkUserName',
    label: '审查人',
    sortable: true
  },
  {
    field: 'problemContent',
    label: t('problem.problemContent')
  },
  {
    field: 'action',
    label: t('userDemo.action'),
    align: 'center',
    fixed: 'right',
    width: 100,
    slots: {
      default: (data: any) => {
        return (
          <>
            {data.row.recheckTime ? null : (
              <BaseButton type="primary" onClick={() => action(data.row)}>
                复检
              </BaseButton>
            )}

            {/* <BaseButton type="danger" onClick={() => delData(data.row)}>
              {t('exampleDemo.del')}
            </BaseButton> */}
          </>
        )
      }
    }
  }
]
const dialogVisible = ref(false)
const dialogTitle = ref('')

const currentRow = ref()
const actionType = ref('')
const action = (row: any) => {
  dialogTitle.value = '复检'
  currentRow.value = row
  dialogVisible.value = true
}

const delLoading = ref(false)
const ids = ref<string[]>([])
const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const { pageSize, currentPage } = tableState
    const res = await getReCheckProblems({
      pageNo: unref(currentPage),
      pageRow: unref(pageSize),
      pageModel: { ...unref(searchParams) }
    })
    return {
      list: res.data.pageModels || [],
      total: res.data.totalCount || 0
    }
  }
  // fetchDelApi: async () => {
  //   const res = await deleteFiles(unref(ids))
  //   return !!res
  // }
})

const { total, loading, dataList, pageSize, currentPage } = tableState
const { getList, getElTableExpose, delList } = tableMethods
const currentDay = new Date()
function getFormattedDate(date) {
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
}
const fifteenDaysAgo = new Date()
fifteenDaysAgo.setDate(fifteenDaysAgo.getDate() - 30)
const v = ref([
  getFormattedDate(fifteenDaysAgo) + ' 00:00:00',
  getFormattedDate(currentDay) + ' 23:59:59'
])
const searchParams = ref({ startTime: v.value[0], endTime: v.value[1] })

onMounted(() => {
  setValues({ date: v, depName: userStore.userInfo?.depName })
})
const setSearchParams = (params: any) => {
  if (params.date) {
    params.startTime = params.date[0]
    params.endTime = params.date[1]
    delete params.date
  }
  searchParams.value = params
  getList()
}

const delData = async (row) => {
  const elTableExpose = await getElTableExpose()
  ids.value = row ? [row.guid] : elTableExpose?.getSelectionRows().map((v) => v.guid) || []
  delLoading.value = true

  await delList(unref(ids).length).finally(() => {
    delLoading.value = false
  })
}

const saveLoading = ref(false)

const save = async () => {
  const elForm = await getElFormExpose()
  const valid = await elForm?.validate().catch((err) => {
    console.log(err)
  })
  if (valid) {
    saveLoading.value = true
    const formData = await getFormData()
    try {
      formData.guid = currentRow.value?.guid
      let res = await addProblemRecheck(formData).finally(async () => {
        if (formData.status) {
          await SetHomeShowApi({
            fileGuid: currentRow.value.fileGuid,
            isShow: currentRow.value.isShow == '1' ? 0 : 1
          })
        }
        saveLoading.value = false
        getList()
      })
    } catch (error) {
      console.log(error)
    } finally {
      saveLoading.value = false
      dialogVisible.value = false
    }
  }
}

const formSchema = ref<FormSchema[]>([
  {
    field: 'recheckContent',
    label: '复检意见',
    component: 'Input',
    componentProps: {
      type: 'textarea'
    }
  },
  {
    field: 'remark',
    label: t('common.remark'),
    component: 'Input',
    componentProps: {
      type: 'textarea'
    }
  },
  {
    field: 'status',
    label: '是否同意完结',
    component: 'RadioGroup',
    componentProps: {
      isButton: true
    },
    optionApi: () => {
      return [
        { label: t('common.agree'), value: 1 },
        { label: t('common.disagree'), value: 0 }
      ]
    }
  }
])

const rules = reactive({
  recheckContent: [required()],
  status: [required()]
})

let arr: DescriptionsSchema[] = []
columns.map((item) => {
  if (item.field !== 'action') {
    arr.push({ field: item.field, label: item.label })
  }
})

const detailSchema = ref<DescriptionsSchema[]>([...arr])
const videoDialogVisible = ref(false)
const videoSrc = ref('')
const showVideoLoading = ref(false)
const lookVideo = async () => {
  videoDialogVisible.value = true
  showVideoLoading.value = true
  const res = await getPalyCutFileApi({ fileGuid: currentRow.value.fileGuid })
  videoSrc.value = res.data
  showVideoLoading.value = false
}

let textV = ref()
const textUrl = ref()
const showDetail = ref(false)
const look = () => {
  showDetail.value = true
  showVideoLoading.value = true
  getPalyCutFileApi({ fileGuid: currentRow.value.guid })
    .then((res) => {
      // const myBlob = new Blob([res.data], { type: 'text/plain' })
      // textUrl.value = URL.createObjectURL(myBlob)
      textUrl.value = res.data
      if (res.data) {
        fetch(res.data)
          .then((response) => response.text())
          .then((data) => {
            textV.value = data
            showVideoLoading.value = false
          })
          .catch((error) => {
            console.log('----------------', error)
            showVideoLoading.value = false
            ElMessage({
              message: '日志加载失败',
              type: 'error'
            })
          })
      }
    })
    .catch(() => {
      showVideoLoading.value = false
      ElMessage({
        message: '日志加载失败',
        type: 'warning'
      })
    })
}
</script>

<template>
  <ContentWrap>
    <Search
      :schema="searchSchema"
      @reset="setSearchParams"
      @search="setSearchParams"
      @register="formRegister"
    />

    <Table
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :reserveIndex="true"
      :columns="columns"
      :data="dataList"
      :loading="loading"
      :pagination="{
        total
      }"
      :showAction="true"
      :rowStyle="rowStyleFC"
    />
    <Dialog v-model="dialogVisible" :title="dialogTitle" :max-height="500">
      <Descriptions :schema="detailSchema" :data="currentRow || {}" />
      <Form :rules="rules" :schema="formSchema" :isCol="false" @register="formRegister" />
      <template #footer>
        <BaseButton
          type="success"
          @click="lookVideo"
          v-if="currentRow.fileType == '视频' || currentRow.fileType == '音频'"
        >
          预览违章{{ currentRow.fileType }}
        </BaseButton>
        <BaseButton type="success" @click="look" v-if="currentRow.fileType == '日志'">
          预览违章日志
        </BaseButton>
        <BaseButton type="success" @click="lookVideo" v-if="currentRow.fileType == '图片'">
          预览违章图片
        </BaseButton>
        <BaseButton type="primary" :loading="saveLoading" @click="save">
          {{ t('exampleDemo.save') }}
        </BaseButton>
        <BaseButton @click="dialogVisible = false">{{ t('dialogDemo.close') }}</BaseButton>
      </template>
    </Dialog>
    <Dialog v-model="videoDialogVisible" title="预览违章视频" :fullscreen="false">
      <video
        v-if="currentRow.fileType == '视频'"
        :src="videoSrc"
        controls
        style="width: 100%; height: 400px; background: #000"
        preload="auto"
        autoplay
        v-loading="showVideoLoading"
      ></video>
      <video
        v-if="currentRow.fileType == '音频'"
        :src="videoSrc"
        autoplay
        controls
        type="audio/mp3"
        style="width: 100%; height: 400px; background-color: #000"
      ></video>
      <div
        style="width: 100%; height: 400px; overflow-y: scroll"
        v-loading="showVideoLoading"
        v-if="currentRow.fileType == '日志'"
      >
        {{ textV }}
      </div>
      <img
        v-if="currentRow.fileType == '图片'"
        :src="videoSrc"
        style="width: 100%; height: 400px"
        v-loading="showVideoLoading"
      />
    </Dialog>
  </ContentWrap>
</template>
